<template>
  <div class="role-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="角色名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 110px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <button-box class="filter-item" type="primary" icon="el-icon-search" text="搜索" @click="handleFilter"></button-box>
      <button-box class="filter-item" type="primary" icon="el-icon-plus" text="添加角色" @click="handleCreate"></button-box>
      <button-box class="filter-item" type="success" icon="el-icon-refresh" text="刷新" @click="handleRefresh"></button-box>
    </div>

    <!-- 添加工具栏 -->
    <div class="table-toolbar" style="margin-bottom: 15px;">
      <button-box type="success" icon="el-icon-download" text="导出" @click="exportRoleList"></button-box>
      <button-box type="danger" icon="el-icon-delete" text="批量删除" :disabled="multipleSelection.length === 0" @click="handleBatchDelete"></button-box>
      <el-dropdown trigger="click">
        <button-box type="info" icon="el-icon-s-grid" text="列设置">
          <i class="el-icon-arrow-down el-icon--right"></i>
        </button-box>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in columnOptions" :key="item.key">
            <el-checkbox v-model="selectedColumns" :label="item.key">{{item.label}}</el-checkbox>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column align="center" label="ID" min-width="80">
        <template #default="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="角色标识" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.code }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="角色名" min-width="150">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="header-center" label="描述" min-width="250">
        <template #default="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" min-width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" min-width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="320">
        <template #default="scope">
          <button-box
            size="mini"
            type="primary"
            text="编辑"
            @click="handleUpdate(scope.row)"
          ></button-box>
          <button-box
            size="mini"
            type="success"
            text="菜单权限"
            @click="handlePermission(scope.row)"
          ></button-box>
          <button-box
            size="mini"
            type="warning"
            text="数据权限"
            @click="handleDataScope(scope.row)"
          ></button-box>
          <button-box
            size="mini"
            type="info"
            text="密码权限"
            @click="handlePasswordPermission(scope.row)"
          ></button-box>
          <button-box
            v-if="scope.row.code !== 'admin'"
            size="mini"
            type="danger"
            text="删除"
            confirm="确认删除该角色?"
            @click="handleDelete(scope.row)"
          ></button-box>
          <button-box
            size="mini"
            type="info"
            text="复制"
            @click="handleCopyRole(scope.row)"
          ></button-box>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="pageSizes"
        :page-size.sync="listQuery.limit"
        :layout="paginationLayout"
        :total="total"
        @size-change="handlePaginationChange"
        @current-change="handlePaginationChange"
      />
    </div>

    <!-- 添加或更新角色对话框 -->
    <dialog-box
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="500px"
      @confirm="dialogStatus==='create'?createData():updateData()"
      @cancel="dialogFormVisible = false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="temp.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="temp.code" placeholder="请输入角色标识，如：admin" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="temp.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </dialog-box>

    <!-- 分配菜单权限对话框 -->
    <dialog-box
      title="分配菜单权限"
      :visible.sync="permissionDialogVisible"
      width="600px"
      @confirm="updateRolePermission"
      @cancel="permissionDialogVisible = false"
    >
      <div class="dialog-tip">
        勾选项目即可为该角色分配对应菜单及功能权限（父子关联）
      </div>
      <div class="permission-tree-toolbar">
        <el-button size="mini" type="primary" @click="handleCheckAllPermission">全选</el-button>
        <el-button size="mini" @click="handleCheckNonePermission">取消全选</el-button>
        <el-button size="mini" type="info" @click="handleExpandAll(true)">展开全部</el-button>
        <el-button size="mini" type="info" @click="handleExpandAll(false)">收起全部</el-button>
      </div>
      <div class="permission-tree-container">
        <el-tree
          ref="permissionTree"
          :data="permissionData"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :check-strictly="false"
          :props="defaultProps"
        />
      </div>
    </dialog-box>
    
    <!-- 分配数据权限对话框 -->
    <dialog-box
      title="分配数据权限"
      :visible.sync="dataScopeDialogVisible"
      width="600px"
      @confirm="updateRoleDataScope"
      @cancel="dataScopeDialogVisible = false"
    >
      <el-form
        ref="dataScopeForm"
        :model="dataScopeForm"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="角色名称">
          <span>{{ currentRole.name }}</span>
        </el-form-item>
        <el-form-item label="权限范围">
          <el-radio-group v-model="dataScopeForm.dataScope">
            <el-radio label="1">全部数据权限</el-radio>
            <el-radio label="2">自定义数据权限</el-radio>
            <el-radio label="3">本部门数据权限</el-radio>
            <el-radio label="4">本部门及以下数据权限</el-radio>
            <el-radio label="5">仅本人数据权限</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="数据权限" v-if="dataScopeForm.dataScope === '2'">
          <el-tree
            ref="deptTree"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
          />
        </el-form-item>
      </el-form>
    </dialog-box>

    <!-- 设置密码修改权限对话框 -->
    <dialog-box
      title="设置密码修改权限"
      :visible.sync="passwordPermissionDialogVisible"
      width="500px"
      @confirm="updatePasswordPermission"
      @cancel="passwordPermissionDialogVisible = false"
    >
      <el-form
        ref="passwordPermissionForm"
        :model="passwordPermissionForm"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="角色名称">
          <span>{{ currentRole.name }}</span>
        </el-form-item>
        <el-form-item label="密码修改权限">
          <el-switch
            v-model="passwordPermissionForm.canChangePassword"
            active-text="允许"
            inactive-text="禁止"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
          <div class="permission-label">
            <span class="permission-status">当前状态：</span>
            <el-tag :type="passwordPermissionForm.canChangePassword ? 'success' : 'danger'" size="small">
              {{ passwordPermissionForm.canChangePassword ? '允许修改密码' : '禁止修改密码' }}
            </el-tag>
          </div>
        </el-form-item>
        <div class="permission-note" v-if="currentRole.code === 'admin'">
          <i class="el-icon-warning"></i>
          <span>超级管理员默认拥有所有权限，此设置仅对其他角色生效</span>
        </div>
      </el-form>
    </dialog-box>
  </div>
</template>

<script>
//api请求预备
// import { getRoleListApi, createRoleApi, updateRoleApi, deleteRoleApi, assignPermissionsApi, getRolePermissionsApi, setPasswordPermissionApi,getMenuTreeApi } from '@/api/role.js'

export default {
  name: 'RoleManagement',
  data() {
    return {
      list: [
        { 
          id: 1, 
          name: '超级管理员', 
          code: 'admin', 
          description: '拥有所有权限', 
          status: '1',
          createTime: '2023-01-01 12:00:00' 
        },
        { 
          id: 2, 
          name: '普通管理员', 
          code: 'manager', 
          description: '拥有部分权限', 
          status: '1',
          createTime: '2023-01-02 12:00:00' 
        },
        { 
          id: 3, 
          name: '用户管理员', 
          code: 'user_manager', 
          description: '只能管理用户', 
          status: '1',
          createTime: '2023-01-03 12:00:00' 
        },
        { 
          id: 4, 
          name: '访客', 
          code: 'visitor', 
          description: '只有查看权限', 
          status: '0',
          createTime: '2023-01-04 12:00:00' 
        }
      ],
      total: 4,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        name: '',
        status: '' // 新增状态筛选
      },
      statusOptions: [ // 新增状态选项
        { label: '全部', value: '' },
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ],
      temp: {
        id: undefined,
        name: '',
        code: '',
        description: '',
        status: '1'
      },
      dialogFormVisible: false,
      permissionDialogVisible: false,
      dataScopeDialogVisible: false,
      passwordPermissionDialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '创建角色'
      },
      rules: {
        name: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '角色标识不能为空', trigger: 'blur' }]
      },
      permissionData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentRole: {},
      dataScopeForm: {
        roleId: null,
        dataScope: '1',
        deptIds: []
      },
      deptOptions: [
        { id: 1, name: '总公司', children: [
          { id: 2, name: '研发部门' },
          { id: 3, name: '市场部门' },
          { id: 4, name: '财务部门' },
          { id: 5, name: '人事部门', children: [
            { id: 6, name: '人力资源组' },
            { id: 7, name: '招聘组' }
          ]}
        ]}
      ],
      passwordPermissionForm: {
        roleId: null,
        canChangePassword: true
      },
      pageSizes: [10, 20, 50, 100],
      paginationLayout: "total, sizes, prev, pager, next, jumper",
      paginationTimer: null,
      // 新增属性
      multipleSelection: [],
      columnOptions: [
        { key: 'id', label: 'ID' },
        { key: 'code', label: '角色标识' },
        { key: 'name', label: '角色名' },
        { key: 'description', label: '描述' },
        { key: 'status', label: '状态' },
        { key: 'createTime', label: '创建时间' }
      ],
      selectedColumns: ['id', 'code', 'name', 'description', 'status', 'createTime'],
      copyPermissionsFrom: null
    }
  },
  created() {
    this.fetchData()
    this.getMenuTree() // 获取菜单树数据
  },
  methods: {
    fetchData() {
      this.listLoading = true
      
      // 实际项目中应该使用API请求
      // getRoleListApi(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // }).catch(() => {
      //   this.listLoading = false
      // })
      
      // 模拟异步请求
      setTimeout(() => {
        // 根据筛选条件过滤数据
        let filteredList = [
          { 
            id: 1, 
            name: '超级管理员', 
            code: 'admin', 
            description: '拥有所有权限', 
            status: '1',
            createTime: '2023-01-01 12:00:00' 
          },
          { 
            id: 2, 
            name: '普通管理员', 
            code: 'manager', 
            description: '拥有部分权限', 
            status: '1',
            createTime: '2023-01-02 12:00:00' 
          },
          { 
            id: 3, 
            name: '用户管理员', 
            code: 'user_manager', 
            description: '只能管理用户', 
            status: '1',
            createTime: '2023-01-03 12:00:00' 
          },
          { 
            id: 4, 
            name: '访客', 
            code: 'visitor', 
            description: '只有查看权限', 
            status: '0',
            createTime: '2023-01-04 12:00:00' 
          }
        ];
        
        // 根据角色名称筛选
        if (this.listQuery.name) {
          filteredList = filteredList.filter(item => 
            item.name.toLowerCase().includes(this.listQuery.name.toLowerCase())
          );
        }
        
        // 根据状态筛选
        if (this.listQuery.status !== '') {
          filteredList = filteredList.filter(item => 
            item.status === this.listQuery.status
          );
        }
        
        this.list = filteredList;
        this.total = filteredList.length;
        this.listLoading = false;
      }, 300)
    },
    // 添加刷新方法
    handleRefresh() {
      // 关闭所有对话框
      this.dialogFormVisible = false
      this.permissionDialogVisible = false
      this.dataScopeDialogVisible = false
      this.passwordPermissionDialogVisible = false
      
      // 重置页码为1
      this.listQuery.page = 1
      
      // 刷新数据
      this.fetchData()
    },
    // 添加getList方法处理分页事件
    getList(val) {
      this.listQuery.page = val.page
      this.listQuery.limit = val.limit
      this.fetchData()
    },
    handlePaginationChange() {
      if (this.paginationTimer) clearTimeout(this.paginationTimer)
      this.paginationTimer = setTimeout(() => this.getList(), 300)
    },
    getMenuTree() {
      // 实际项目中应该使用API请求
      // getMenuTreeApi().then(response => {
      //   this.permissionData = response.data
      // })
      
      // 模拟菜单数据
      this.permissionData = [
        {
          id: 1,
          name: '系统管理',
          path: '/system',
          component: 'Layout',
          perms: 'system',
          icon: 'el-icon-setting',
          type: 'C',
          sort: 1,
          status: '1',
          children: [
            {
              id: 11,
              name: '用户管理',
              path: '/system/user',
              component: 'system/user/index',
              perms: 'system:user',
              icon: 'el-icon-user',
              type: 'M',
              sort: 1,
              status: '1',
              children: [
                {
                  id: 111,
                  name: '用户查询',
                  perms: 'system:user:query',
                  type: 'F',
                  sort: 1,
                  status: '1'
                },
                {
                  id: 112,
                  name: '用户新增',
                  perms: 'system:user:add',
                  type: 'F',
                  sort: 2,
                  status: '1'
                },
                {
                  id: 113,
                  name: '用户修改',
                  perms: 'system:user:edit',
                  type: 'F',
                  sort: 3,
                  status: '1'
                },
                {
                  id: 114,
                  name: '用户删除',
                  perms: 'system:user:remove',
                  type: 'F',
                  sort: 4,
                  status: '1'
                },
                {
                  id: 115,
                  name: '重置密码',
                  perms: 'system:user:resetPwd',
                  type: 'F',
                  sort: 5,
                  status: '1'
                }
              ]
            },
            {
              id: 12,
              name: '角色管理',
              path: '/system/role',
              component: 'system/role/index',
              perms: 'system:role',
              icon: 'el-icon-user-solid',
              type: 'M',
              sort: 2,
              status: '1'
            },
            {
              id: 13,
              name: '菜单管理',
              path: '/system/menu',
              component: 'system/menu/index',
              perms: 'system:menu',
              icon: 'el-icon-menu',
              type: 'M',
              sort: 3,
              status: '1'
            }
          ]
        },
      ]
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        code: '',
        description: '',
        status: '1'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // 实际项目中应该使用API请求
          // createRoleApi(this.temp).then(() => {
          //   this.dialogFormVisible = false
          //   this.$messageBox.success('创建成功')
          //   this.fetchData()
          // })
          
          // 模拟API调用
          const newId = Math.max(...this.list.map(item => item.id)) + 1
          const newRole = {...this.temp, id: newId, createTime: new Date().toLocaleString()}
          this.list.unshift(newRole)
          this.dialogFormVisible = false
          this.$messageBox.success('创建成功')
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // 实际项目中应该使用API请求
          // const tempData = Object.assign({}, this.temp)
          // updateRoleApi(tempData).then(() => {
          //   this.dialogFormVisible = false
          //   this.$messageBox.success('更新成功')
          //   this.fetchData()
          // })
          
          // 模拟API调用
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$messageBox.success('更新成功')
        }
      })
    },
    
    handleDelete(row) {
      // 使用ButtonBox的confirm属性代替这里的确认对话框
        // 实际项目中应该使用API请求
        // deleteRoleApi(row.id).then(() => {
      //   this.$messageBox.success('删除成功')
        //   this.fetchData()
        // })
        
        // 模拟API调用
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1)
      this.$messageBox.success('删除成功')
    },
    handlePermission(row) {
      this.currentRole = row
      this.permissionDialogVisible = true
      
      // 实际项目中应该获取角色已有的权限
      // getRolePermissionsApi(row.id).then(res => {
      //   const checkedKeys = res.data.menuIds
      //   this.$nextTick(() => {
      //     if (this.$refs.permissionTree) {
      //       this.$refs.permissionTree.setCheckedKeys(checkedKeys)
      //     }
      //   })
      // })
      
      // 模拟获取角色权限
      const checkedKeys = row.id === 1 ? [1, 11, 12, 13, 2, 21, 22, 111, 112, 113, 114, 115] : // 超级管理员拥有所有权限
                          row.id === 2 ? [1, 11, 12, 2, 111, 112] : // 普通管理员拥有部分权限
                          row.id === 3 ? [1, 11, 111, 112] : // 用户管理员只有用户相关权限
                          [] // 访客没有权限
                          
      this.$nextTick(() => {
        if (this.$refs.permissionTree) {
          this.$refs.permissionTree.setCheckedKeys(checkedKeys)
        }
      })
    },
    updateRolePermission() {
      const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
      const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
      const menuIds = [...checkedKeys, ...halfCheckedKeys]
      
      // 实际项目中应该调用API
      // assignPermissionsApi({
      //   roleId: this.currentRole.id,
      //   menuIds
      // }).then(() => {
      //   this.permissionDialogVisible = false
      //   this.$messageBox.success('权限分配成功')
      // })
      
      // 模拟API调用
      console.log('分配权限成功：', {
        roleId: this.currentRole.id,
        menuIds
      })
      this.permissionDialogVisible = false
      this.$messageBox.success('权限分配成功')
    },
    handleDataScope(row) {
      this.currentRole = row
      this.dataScopeForm.roleId = row.id
      
      // 根据角色ID设置数据范围，这里简单模拟
      if (row.id === 1) {
        this.dataScopeForm.dataScope = '1' // 超级管理员 - 全部数据权限
      } else if (row.id === 2) {
        this.dataScopeForm.dataScope = '4' // 普通管理员 - 本部门及以下数据权限
      } else if (row.id === 3) {
        this.dataScopeForm.dataScope = '2' // 用户管理员 - 自定义数据权限
        
        // 模拟已选择的部门ID
        this.$nextTick(() => {
          if (this.$refs.deptTree) {
            this.$refs.deptTree.setCheckedKeys([2, 5]) // 选中"研发部门"和"人事部门"
          }
        })
      } else {
        this.dataScopeForm.dataScope = '5' // 访客 - 仅本人数据权限
      }
      
      this.dataScopeDialogVisible = true
    },
    updateRoleDataScope() {
      // 实际项目中应该调用API
      // const deptIds = this.dataScopeForm.dataScope === '2' ? 
      //   this.$refs.deptTree.getCheckedKeys() : []
      
      // const params = {
      //   roleId: this.currentRole.id,
      //   dataScope: this.dataScopeForm.dataScope,
      //   deptIds
      // }
      
      // updateRoleDataScopeApi(params).then(() => {
      //   this.dataScopeDialogVisible = false
      //   this.$messageBox.success('数据权限更新成功')
      // })
      
      // 模拟API调用
      console.log('数据权限更新成功：', {
        roleId: this.currentRole.id,
        dataScope: this.dataScopeForm.dataScope
      })
      this.dataScopeDialogVisible = false
      this.$messageBox.success('数据权限更新成功')
    },
    
    handlePasswordPermission(row) {
      this.currentRole = row
      this.passwordPermissionForm.roleId = row.id
      
      // 根据角色设置是否允许修改密码，简单模拟
      this.passwordPermissionForm.canChangePassword = row.id === 1 || row.id === 2
      
      this.passwordPermissionDialogVisible = true
    },
    
    updatePasswordPermission() {
      // 实际项目中应该调用API
      // const params = {
      //   roleId: this.currentRole.id,
      //   canChangePassword: this.passwordPermissionForm.canChangePassword
      // }
      
      // setPasswordPermissionApi(params).then(() => {
      //   this.passwordPermissionDialogVisible = false
      //   this.$messageBox.success('密码修改权限设置成功')
      // })
      
      // 模拟API调用
      console.log('密码修改权限设置成功：', {
        roleId: this.currentRole.id,
        canChangePassword: this.passwordPermissionForm.canChangePassword
      })
      this.passwordPermissionDialogVisible = false
      this.$messageBox.success('密码修改权限设置成功')
    },
    // 权限树全选功能
    handleCheckAllPermission() {
      // 获取所有节点的ID
      const allKeys = []
      const getNodeKeys = (data) => {
        data.forEach(node => {
          allKeys.push(node.id)
          if (node.children && node.children.length) {
            getNodeKeys(node.children)
          }
        })
      }
      getNodeKeys(this.permissionData)
      
      this.$refs.permissionTree.setCheckedKeys(allKeys)
    },

    // 权限树取消全选功能
    handleCheckNonePermission() {
      this.$refs.permissionTree.setCheckedKeys([])
    },
    
    // 权限树展开/收起全部
    handleExpandAll(expand) {
      const treeRef = this.$refs.permissionTree
      const nodes = treeRef.store._getAllNodes()
      nodes.forEach(node => {
        node.expanded = expand
      })
    },
    
    // 表格多选
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$messageBox.warning('请先选择要删除的角色')
        return
      }
      
      // 检查是否有admin角色
      const hasAdmin = this.multipleSelection.some(item => item.code === 'admin')
      if (hasAdmin) {
        this.$messageBox.warning('超级管理员角色不能删除')
        return
      }
      
      const ids = this.multipleSelection.map(item => item.id)
      
      this.$confirm('确认要批量删除所选角色吗？', '批量删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中应该调用API
        // batchDeleteRolesApi(ids).then(() => {
        //   this.$messageBox.success('批量删除成功')
        //   this.fetchData()
        // })
        
        // 模拟API调用
        this.list = this.list.filter(item => !ids.includes(item.id))
        this.$messageBox.success('批量删除成功')
      }).catch(() => {})
    },
    
    // 导出角色列表
    exportRoleList() {
      const headers = this.columnOptions
        .filter(col => this.selectedColumns.includes(col.key))
        .map(col => col.label)
      
      const exportData = this.list.map(row => {
        const item = {}
        this.selectedColumns.forEach((key, index) => {
          // 特殊处理状态列
          if (key === 'status') {
            item[headers[index]] = row[key] === '1' ? '启用' : '禁用'
          } else {
            item[headers[index]] = row[key]
          }
        })
        return item
      })
      
      // 实际项目中应该调用Excel导出工具
      console.log('导出数据:', exportData)
      this.$messageBox.success('角色数据导出成功')
      
      // 实际项目中的导出代码示例
      // import('@/utils/excel').then(excel => {
      //   excel.exportExcel(exportData, '角色列表')
      // })
    },
    
    // 复制角色
    handleCopyRole(row) {
      this.resetTemp()
      
      // 复制角色基本信息，但生成新的角色标识
      this.temp = {
        name: `${row.name} - 副本`,
        code: `${row.code}_copy`,
        description: row.description,
        status: row.status
      }
      
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
      
      // 记录源角色ID，用于权限复制
      this.copyPermissionsFrom = row.id
    }
  }
}
</script>

<style lang="scss" scoped>
.role-container {
  padding: 0;

  .filter-container {
    margin-bottom: 15px;
    padding: 8px 0;
    background-color: var(--bg-container);
    border-radius: 4px;
    padding: 15px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    .filter-item {
      margin-right: 10px;
      height: 32px;
      line-height: 1;
      padding: 7px 15px;

      &.el-input {
        width: 200px;
      }
    }
  }

  .table-toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px 15px;
    background-color: var(--bg-container);
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    .button-box {
      margin-right: 10px;
    }
    
    .el-dropdown {
      margin-left: auto;
    }
  }

  .dialog-tip {
    margin-bottom: 10px;
    color: #606266;
    font-size: 14px;
  }

  .permission-tree-toolbar {
    display: flex;
    margin-bottom: 10px;
    padding: 5px 0;
    
    .el-button {
      margin-right: 10px;
    }
  }

  .permission-tree-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
  }
  
  .permission-note {
    color: #E6A23C;
    font-size: 14px;
    padding: 5px 0;
    
    i {
      margin-right: 5px;
    }
  }
  
  .permission-label {
    margin-top: 10px;
    
    .permission-status {
      margin-right: 5px;
      color: #606266;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  .el-table {
    margin-bottom: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    overflow: hidden;
    
    .el-button--mini {
      padding: 5px 8px;
      font-size: 12px;
    }
    
    .button-box {
      margin: 0 3px;
    }
  }
}
</style> 